{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e620997c-d053-4fcf-ac7c-70f488c7cab1",
   "metadata": {},
   "source": [
    "# 优化器\n",
    "\n",
    "原文: https://www.runoob.com/scipy/scipy-optimize.html\n",
    "\n",
    "## 一、求解"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "f028aa36-c41f-420a-8137-7aafe543855c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[-1.]\n",
      "    fjac: array([[-1.]])\n",
      "     fun: array([0.])\n",
      " message: 'The solution converged.'\n",
      "    nfev: 4\n",
      "     qtf: array([2.18114415e-12])\n",
      "       r: array([-1.])\n",
      "  status: 1\n",
      " success: True\n",
      "       x: array([-1.])\n"
     ]
    }
   ],
   "source": [
    "from scipy.optimize import root\n",
    "from math import cos\n",
    "\n",
    "def eqn(x):\n",
    "  return x + cos(x)\n",
    "\n",
    "def eqn1(x):\n",
    "    return x + 1\n",
    "\n",
    "myroot = root(eqn1, 0)\n",
    "\n",
    "print(myroot.x)\n",
    "# 查看更多信息\n",
    "print(myroot)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "75e56195-5720-42d3-a650-beef2276385a",
   "metadata": {},
   "source": [
    "## 二、最小化函数\n",
    "\n",
    "x^2 + x + 2 使用 BFGS 的最小化函数:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "e61b03a2-ba2f-4782-9b03-4586561710d3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "      fun: 1.75\n",
      " hess_inv: array([[0.50000001]])\n",
      "      jac: array([0.])\n",
      "  message: 'Optimization terminated successfully.'\n",
      "     nfev: 8\n",
      "      nit: 2\n",
      "     njev: 4\n",
      "   status: 0\n",
      "  success: True\n",
      "        x: array([-0.50000001])\n"
     ]
    }
   ],
   "source": [
    "from scipy.optimize import minimize\n",
    "\n",
    "def eqn(x):\n",
    "  return x**2 + x + 2\n",
    "\n",
    "mymin = minimize(eqn, 0, method='BFGS')\n",
    "\n",
    "print(mymin)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "74fa5da5-d083-4f6f-ae6e-8baab8b59c46",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
